<template>
  <div class="query-container">
    <!-- 左侧表单区域 -->
    <div class="form-section">
      <h3 class="form-title">查询信息</h3>
      <el-form :model="queryForm" :rules="rules" ref="queryFormRef" label-width="100px">
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="queryForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="queryForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="流域ID" prop="basinId">
          <el-input v-model="queryForm.basinId" placeholder="请输入流域ID" />
        </el-form-item>
        <el-form-item label="备注" prop="request">
          <el-input v-model="queryForm.request" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getHistoryData">查询历史数据</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="content-section">
      <el-table
        v-loading="loading"
        :data="historyData"
        style="width: 100%"
        border
      >
        <el-table-column
          prop="id"
          label="相似度"
          width="180"
        />
        <el-table-column
          prop="name"
          label="洪水名字"
          width="180"
        />
        <el-table-column
          prop="detailUrl"
          label="详细数据"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click.prevent="fetchDetailData(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 图表展示区域 -->
      <div v-if="chartData" class="charts-container">
        <!-- 流量折线图 -->
        <div ref="flowChartRef" class="chart"></div>
        <!-- 降雨量柱状图 -->
        <div ref="rainfallChartRef" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const route = useRoute()
const loading = ref(false)
const historyData = ref([])
const flowChartRef = ref(null)
const rainfallChartRef = ref(null)
const chartData = ref(null)
let flowChart = null
let rainfallChart = null

// 表单校验规则
const rules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  basinId: [{ required: true, message: '请输入流域ID', trigger: 'blur' }]
}

// 查询表单数据
const queryForm = ref({
  startTime: '',
  endTime: '',
  basinId: '',
  request: ''
})
const queryFormRef = ref(null)

// 获取历史数据
const getHistoryData = async () => {
  try {
    await queryFormRef.value.validate()
    loading.value = true

    const startTime = Math.floor(new Date(queryForm.value.startTime).getTime() / 1000)
    const endTime = Math.floor(new Date(queryForm.value.endTime).getTime() / 1000)
    const { basinId, request } = queryForm.value

    if (isNaN(startTime) || isNaN(endTime) || startTime >= endTime) {
      ElMessage.warning('请选择有效的时间范围')
      return
    }

    const response = await fetch('http://10.10.10.125:8002/api/history_data', {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        start_time: startTime,
        end_time: endTime,
        basin_id: basinId,
        request: request
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    
    if (data.status === 'success' && data.resources) {
      // 处理数据，添加完整的详细数据URL
      historyData.value = data.resources.map(item => ({
        ...item,
        detailUrl: `http://10.10.10.125:8002/api/${item.history_segment}`
      }))
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    console.error('获取历史数据失败:', error)
    ElMessage.error(`获取历史数据失败: ${error.message}`)
    historyData.value = []
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = () => {
  if (!chartData.value) return

  // 初始化流量折线图
  if (!flowChart) {
    flowChart = echarts.init(flowChartRef.value)
  }
  
  // 初始化降雨量柱状图
  if (!rainfallChart) {
    rainfallChart = echarts.init(rainfallChartRef.value)
  }

  const { current_data, similar_history_segments } = chartData.value
  
  // 设置流量折线图配置
  const flowOption = {
    title: { text: '流量对比图' },
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['当前流量', '当前预测流量', '当前预测+10天流量',
             '历史流量', '历史预测流量', '历史预测+10天流量']
    },
    xAxis: { type: 'category', data: current_data.time },
    yAxis: { type: 'value', name: '流量' },
    series: [
      {
        name: '当前流量',
        type: 'line',
        data: current_data.flow,
        lineStyle: { color: '#0066CC' }
      },
      {
        name: '当前预测流量',
        type: 'line',
        data: current_data.current_time_data.map(item => item.flow),
        lineStyle: { color: '#003366' }
      },
      {
        name: '当前预测+10天流量',
        type: 'line',
        data: current_data.after10_label_data.map(item => item.flow),
        lineStyle: { color: '#99CCFF' }
      },
      {
        name: '历史流量',
        type: 'line',
        data: similar_history_segments.flow,
        lineStyle: { color: '#006633' }
      },
      {
        name: '历史预测流量',
        type: 'line',
        data: similar_history_segments.data.map(item => item.flow),
        lineStyle: { color: '#003300' }
      },
      {
        name: '历史预测+10天流量',
        type: 'line',
        data: similar_history_segments.after10_data.map(item => item.flow),
        lineStyle: { color: '#99CC99' }
      }
    ]
  }

  // 设置降雨量柱状图配置
  const rainfallOption = {
    title: { text: '降雨量对比图' },
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['当前降雨量', '当前预测降雨量', '当前预测+10天降雨量',
             '历史降雨量', '历史预测降雨量', '历史预测+10天降雨量']
    },
    xAxis: { type: 'category', data: current_data.time },
    yAxis: { type: 'value', name: '降雨量' },
    series: [
      {
        name: '当前降雨量',
        type: 'bar',
        data: current_data.rainfall,
        itemStyle: { color: '#0066CC' }
      },
      {
        name: '当前预测降雨量',
        type: 'bar',
        data: current_data.current_time_data.map(item => item.rainfall),
        itemStyle: { color: '#003366' }
      },
      {
        name: '当前预测+10天降雨量',
        type: 'bar',
        data: current_data.after10_label_data.map(item => item.rainfall),
        itemStyle: { color: '#99CCFF' }
      },
      {
        name: '历史降雨量',
        type: 'bar',
        data: similar_history_segments.rainfall,
        itemStyle: { color: '#006633' }
      },
      {
        name: '历史预测降雨量',
        type: 'bar',
        data: similar_history_segments.data.map(item => item.rainfall),
        itemStyle: { color: '#003300' }
      },
      {
        name: '历史预测+10天降雨量',
        type: 'bar',
        data: similar_history_segments.after10_data.map(item => item.rainfall),
        itemStyle: { color: '#99CC99' }
      }
    ]
  }

  flowChart.setOption(flowOption)
  rainfallChart.setOption(rainfallOption)
}

// 获取详细数据并展示图表
const fetchDetailData = async (row) => {
  try {
    loading.value = true
    const response = await fetch(row.detailUrl)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    if (data.status === 'success') {
      chartData.value = data
      nextTick(() => {
        initCharts()
      })
    } else {
      throw new Error('获取详细数据失败')
    }
  } catch (error) {
    console.error('获取详细数据失败:', error)
    ElMessage.error(`获取详细数据失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 组件挂载时，如果有路由参数则自动填充表单并查询
onMounted(() => {
  const { startTime, endTime, basinId, request } = route.query
  if (startTime && endTime && basinId && request) {
    queryForm.value = {
      startTime: new Date(parseInt(startTime) * 1000).toISOString().slice(0, 16).replace('T', ' '),
      endTime: new Date(parseInt(endTime) * 1000).toISOString().slice(0, 16).replace('T', ' '),
      basinId,
      request
    }
    getHistoryData()
  }

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    flowChart?.resize()
    rainfallChart?.resize()
  })
})

// 组件卸载时销毁图表实例
onUnmounted(() => {
  flowChart?.dispose()
  rainfallChart?.dispose()
  window.removeEventListener('resize', () => {
    flowChart?.resize()
    rainfallChart?.resize()
  })
})
</script>

<style scoped>
.query-container {
  display: flex;
  height: 100%;
  width: 100%;
}

.form-section {
  width: 20%;
  padding: 20px;
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.form-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.content-section {
  width: 80%;
  padding: 20px;
  overflow-y: auto;
}

.charts-container {
  margin-top: 20px;
}

.chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}
</style>